package com.wgke.bluetooth.utils;

public class ByteArrayProcessor {
    private static final byte HEADER_FIRST = (byte) 0x5A;
    private static final byte HEADER_SECOND = (byte) 0xA5;
    private static final byte FOOTER = (byte) 0xAA;

    private byte[] buffer = new byte[0];
    private OnPacketReceivedListener listener;

    public interface OnPacketReceivedListener {
        void onPacketReceived(byte[] packet);
    }

    public ByteArrayProcessor(OnPacketReceivedListener listener) {



        this.listener = listener;
    }

    public void process(byte[] newData) {
        // 将新数据追加到缓冲区
        byte[] newBuffer = new byte[buffer.length + newData.length];
        System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
        System.arraycopy(newData, 0, newBuffer, buffer.length, newData.length);
        buffer = newBuffer;

        // 处理缓冲区中的数据
        while (true) {
            int packetLength = tryFindPacket();
            if (packetLength == -1) {
                break; // 没有找到完整的数据包
            }

            // 提取完整的数据包
            byte[] packet = new byte[packetLength];
            System.arraycopy(buffer, 0, packet, 0, packetLength);

            // 通知监听器
            if (listener != null) {
                listener.onPacketReceived(packet);
            }

            // 从缓冲区中移除已处理的数据
            byte[] remainingBuffer = new byte[buffer.length - packetLength];
            System.arraycopy(buffer, packetLength, remainingBuffer, 0, remainingBuffer.length);
            buffer = remainingBuffer;
        }
    }

    private int tryFindPacket() {
        if (buffer.length < 5) { // 最小包长度: 2字节头 + 1字节长度 + 1字节数据 + 2字节校验和 + 1字节结尾
            return -1;
        }

        // 查找包头
        int startIndex = -1;
        for (int i = 0; i <= buffer.length - 2; i++) {
            if (buffer[i] == HEADER_FIRST && buffer[i+1] == HEADER_SECOND) {
                startIndex = i;
                break;
            }
        }

        if (startIndex == -1) {
            // 没有找到包头，可以丢弃这些数据
            buffer = new byte[0];
            return -1;
        }

        // 检查是否有足够的数据（至少到长度字段）
        if (startIndex + 2 >= buffer.length) {
            return -1;
        }

        // 获取正文长度（第三个字节）
        int bodyLength = buffer[startIndex + 2] & 0xFF; // 无符号转换

        // 计算预期的总包长度
        int expectedPacketLength = 3 + bodyLength + 2 + 1; // 头(2)+长度(1)+正文+校验和(2)+结尾(1)

        // 检查是否有足够的数据
        if (buffer.length - startIndex < expectedPacketLength) {
            return -1;
        }

        // 检查包尾
        if (buffer[startIndex + expectedPacketLength - 1] != FOOTER) {
            // 包尾不匹配，跳过这个包头继续查找
            byte[] newBuffer = new byte[buffer.length - startIndex - 2];
            System.arraycopy(buffer, startIndex + 2, newBuffer, 0, newBuffer.length);
            buffer = newBuffer;
            return tryFindPacket();
        }

        // 验证校验和
        int calculatedSum = 0;
        int bodyStart = startIndex + 3;
        int bodyEnd = bodyStart + bodyLength;
        for (int i = bodyStart; i < bodyEnd; i++) {
            calculatedSum += buffer[i] & 0xFF;
        }

        int receivedSum = ((buffer[bodyEnd] & 0xFF) << 8) | (buffer[bodyEnd + 1] & 0xFF);

        if (calculatedSum != receivedSum) {
            // 校验和失败，跳过这个包头继续查找
            byte[] newBuffer = new byte[buffer.length - startIndex - 2];
            System.arraycopy(buffer, startIndex + 2, newBuffer, 0, newBuffer.length);
            buffer = newBuffer;
            return tryFindPacket();
        }

        // 返回完整包的长度
        return expectedPacketLength;
    }
}